<template>
    <eui-page-frame topHeight="170" bottomHeight="124">
        <template #top>
            <view class="navigation">
                <eui-nav-bar :title="title" color="#000000" rightIcon="" />
            </view>
        </template>
        <eui-page-content>
            <eui-base-card title="申请信息">
                <eui-detail-show :items="dataItems" v-model="mainData" labelWidth="80px"></eui-detail-show>

                <UploadFile :autoUpload="false" :disabled="true" :readonly=true fileMediatype="image"
                    :fileId="mainData.c_id" fileClass="物业服务申请单" return-type="array" mode="grid">
                </UploadFile>
            </eui-base-card>

            <eui-popup ref="popup" background-color="#f8f8f8" type="center" :mask-click="false">
                <eui-base-card title="分配工单">
                    <eui-card-input v-model="mainData.c_handle_user" title="处理人" type="text" alignType="left"
                        placeholder="请选择处理人" displayable="false" rightIconType="right"
                        @iconClick="selectOpen('user')" />

                    <eui-card-input v-model="mainData.c_handle_adname" title="处理部门" type="text" alignType="left"
                        placeholder="请选择处理部门" displayable="false" rightIconType="right"
                        @iconClick="selectOpen('depart')" />

                    <eui-card-input v-model="mainData.c_plan_hours" title="计划工时" type="number2" alignType="right"
                        maxlength="4" placeholder="请输入计划工时" />

                    <view class="bt-button bottom-mt">
                        <eui-button type="max2" title="取消" singleTag="取消" @buttonClick="close"></eui-button>
                        <eui-button type="max" title="确认" singleTag="确认2" @buttonClick="confirm"></eui-button>
                    </view>
                </eui-base-card>
            </eui-popup>
        </eui-page-content>
        <template #bottom>
            <view class="bottom bt-button">
                <eui-button type="primary" title="分配" @click="assign" />
            </view>
        </template>
    </eui-page-frame>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';
import useService from '@/hooks/useService';
import UploadFile from '@/components/UploadFile.vue';
import { getRelatedName, getOtherStorageName , getDictName, getStoreRelatedName } from '../components/RelatedName.js';
import { checkIntNum } from '../../../hooks/useValidateMethod.js';

const service = useService({ prefix: "apiApi" });

const id = ref('');
const project = ref('');
const title = ref('工单详情');
const mainData = ref({
    c_task_id: '',
    c_handle_userno: '',
    c_handle_user: '',
    c_handle_adno: '',
    c_handle_adname: '',
    c_plan_hours: 1,
    c_id: '',
});
const popup = ref<any>(null);
const uniqueKey = '管易通物业模块服务';

const dataItems = ref([
    {
        label: "机构",
        prop: "c_store_name",
        type: "text",
        element: {
        },
    },
    {
        label: "所属类型",
        prop: "c_property_type",
        type: "text",
        element: {
        },
    },
    {
        label: "紧急程度",
        prop: "c_urgent",
        type: "text",
        element: {
        },
    },
    {
        label: "商户",
        prop: "c_provider_name",
        type: "text",
        element: {
        },
    },
    {
        label: "铺位",
        prop: "c_counter_no",
        type: "text",
        element: {
        },
    },
    {
        label: "合同号",
        prop: "c_con_no",
        type: "text",
        element: {
        },
    },
    {
        label: "申请来源",
        prop: "c_req_src",
        type: "text",
        element: {
        },
    },
    {
        label: "申请人",
        prop: "c_req_user",
        type: "text",
        element: {
        },
    },
    {
        label: "联系电话",
        prop: "c_req_phone",
        type: "text",
        element: {
        },
    },

    {
        label: "申请时间",
        prop: "c_req_dt",
        type: "text",
        element: {
            mode: 'YYYY-MM-DD HH:mm:ss'
        },
    },
    {
        label: "详情",
        prop: "c_question",
        type: "text",
        element: {
        },
    }
]);

const close = () => {
    mainData.value.c_handle_user = '';
    mainData.value.c_handle_userno = '';
    mainData.value.c_handle_adname = '';
    mainData.value.c_handle_adno = '';
    popup.value.close();
}


const confirm = async () => {
    if (!mainData.value.c_handle_userno) {
        uni.showToast({ title: '请选择处理人', icon: 'none', duration: 2000 });
        return;
    }
    if (!mainData.value.c_handle_adno) {
        uni.showToast({ title: '请选择处理部门', icon: 'none', duration: 2000 });
        return;
    }
    if (!mainData.value.c_plan_hours) {
        uni.showToast({ title: '请输入计划工时', icon: 'none', duration: 2000 });
        return;
    }
    else{
        if(!checkIntNum(mainData.value.c_plan_hours))
        {
            uni.showToast({ title: '计划工时请输入0到24中间的整数', icon: 'none', duration: 2000 });
            return;
        }
        else {
            if(mainData.value.c_plan_hours<0 || mainData.value.c_plan_hours>24){
                uni.showToast({ title: '计划工时必须在0和24中间', icon: 'none', duration: 2000 });
                return;
            }
        }
    }
    await assignService();
}

const assignService = async () => {
    uni.showLoading({ title: "分配中...", mask: true });
    const res = await service.request(uniqueKey, 'AssignWork', 
    { 
        id: mainData.value.c_task_id,
        to_userno: mainData.value.c_handle_userno,
        adno: mainData.value.c_handle_adno,
        plan_hours: mainData.value.c_plan_hours
     });
    uni.hideLoading();
    if (res) {
        popup.value.close();
        uni.showToast({ title: '分配成功', icon: 'none', duration: 2000 });
        uni.navigateBack();
    }
    
}

const assign = () => {
    popup.value.open();
}

onLoad((req) => {
    console.log('onLoadreq', req)
    id.value = req?.id;
    project.value = decodeURIComponent(req?.project);
    title.value = project.value + '工单详情';
    getData();
})

const getData = async () => {
    uni.showLoading({ title: "查询中...", mask: true });
    const res = await service.request(uniqueKey, 'ServiceRequestQuery', { BillId: id.value });
    console.log('getBillData', res)
    uni.hideLoading();
    if (res) {
        const resObject = res;
        if (resObject) {
            const data=resObject.ds[0];
            const billDetail = resObject.ds1;
            mainData.value =
            {
                ...data,
                c_store_name: data.c_store_id ? '[' + data.c_store_id + ']' + getStoreRelatedName(data.c_store_id) : '',
                c_provider_name: data.c_provider ? '[' + data.c_provider + ']' + getRelatedName('rdsProviders', data.c_provider) : '',
                c_property_type: getOtherStorageName('物业服务类型',data.c_property_type),
                c_urgent: getDictName('物业服务申请紧急程度', data.c_urgent),
                c_counter_no: data.c_counter_no ? '[' + data.c_counter_no + ']' + getRelatedName('rdsCounter', data.c_counter_no) : '',
                c_req_src: getDictName('物业服务申请来源', data.c_req_src),
            };

            billDetail && billDetail.map(
                item => {
                    if (dataItems.value.every((x) => x.label != item.c_title)) {
                        dataItems.value.push({
                            label: item.c_title,
                            prop: 'value' + item.c_sort,
                            type: "text",
                            element: {
                            },
                        })
                    }
                    mainData.value['value' + item.c_sort] = item.c_options ? JSON.parse(item.c_options).filter(x => item.c_value.includes(x.value)).map(x => x.title).join(',') : item.c_value
                })

        }
    }
}

/**选择弹出框 */
const selectOpen = (selectType: string) => {
    uni.navigateTo({
        url: `../modals/index?type=${selectType}`
    });
}

const SelectionChanged = (type, item) => {
    console.log('SelectionChanged', type, item)
    switch (type) {
        case 'user':
            mainData.value.c_handle_user = '[' + item.value + ']' + item.text;
            mainData.value.c_handle_userno = item.value;
            break;
        case 'depart':
            mainData.value.c_handle_adno = item.value;
            mainData.value.c_handle_adname = '[' + item.value + ']' + item.text;
            break;
    }
}

defineExpose({
    SelectionChanged
})

</script>

<style lang="scss">
.navigation {
    background: #FFFFFF;
    flex: 0 0 auto;
    margin-bottom: 0rpx;
}

.bottom {
    background-color: white;
    padding: 20rpx;
    height: 80rpx;
    width: 96%;
    bottom: 20rpx;
    right: 0rpx;
    position: fixed;
    margin-bottom: -20rpx;
}

.bt-button {
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.bottom-mt {
    margin-top: 20rpx;
}
</style>